package jupiter.servlets;

import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.mortbay.jetty.RetryRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


//import jupiter.messaging.Inbox;
import jupiter.message.Message;
import jupiter.util.*;

import org.json.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jupiter.channel.Session;
import jupiter.filters.*;

public class JabberServlet extends HttpServlet {
	static Logger logger = LoggerFactory.getLogger(JabberServlet.class);
	public void service(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
		String from = req.getParameter("from");
		String to = req.getParameter("to");
		String message = req.getParameter("message");
		String jabberID = Pattern.compile("/.*").matcher(from).replaceAll("");
		String name = getNameFromJabberID(jabberID);
		
		// TODO implement these things
		Pattern domainp = Pattern.compile("(.*)@.*");
		Matcher matcher = domainp.matcher(to);
		boolean matchFound = matcher.find();
		String refererDomain = "file";
		if(matchFound) refererDomain = matcher.group(1).toLowerCase();
		String newTo = refererDomain+"/@"+Application.getProperty("host");
		String newFrom = refererDomain+"/jabber@"+Application.getProperty("host");
		
		JSONObject messageObj = new JSONObject();
		try {
			messageObj.put("type", "message");
			messageObj.put("action", "create");
			messageObj.put("to", newTo);
			messageObj.put("from", newFrom);
			JSONObject data = new JSONObject();
			data.put("body", message);
			data.put("name", name);
			messageObj.put("data", data);
		} catch (JSONException e1) {
			logger.error("JabberParsing Error", e1);
		}
		// check User
		
		// check Domain
		
		// create Message
		Message m = null;
		try {
			m = new Message(messageObj.toString());
			m.page(refererDomain);
			m.save();
		} catch (FilterException e) {
			logger.error("Filter Exception Error", e);
		}
		String message_json = m.toString();
		if(MessageServlet.subscriber != null)
			MessageServlet.subscriber.sendText(message_json);
		res.setContentType("text/plain");
		res.getWriter().print("hey there");
		res.getWriter().flush();
	}
	/**
	 * Gets the correct name from the database, using the person's jabberID to look it up
	 * @param jabberID
	 * @return
	 */
	static private String getNameFromJabberID(String jabberID){
		String jsonstr = null;
		try{
			jsonstr = (String) (new DBConnection() {
				public Object run(Object jid) throws SQLException{
					String jabberID = (String) jid;
					prepareStatement("Select message_name from users WHERE jabber_id = ?;");
					pstmt.setString(1, jabberID);
					executeQuery();
					boolean has = rs.next();
					if(!has) return null;
					return  rs.getString("message_name");
					
				}
			}).exec(jabberID);
		}catch(SQLException sqle){
			JabberServlet.logger.error("SQL Exception Error", sqle);
		}
		return jsonstr;
	}
}
